<?php
/**
 * Magento Enterprise Edition
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Magento Enterprise Edition License
 * that is bundled with this package in the file LICENSE_EE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.magentocommerce.com/license/enterprise-edition
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category    Mage
 * @package     Mage_Customer
 * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
 * @license     http://www.magentocommerce.com/license/enterprise-edition
 */

/**
 * Abstract API2 class for customer
 *
 * @category   Mage
 * @package    Mage_Customer
 * @author     Magento Core Team <core@magentocommerce.com>
 */
abstract class Silk_Mapi_Model_Api2_Account_Rest extends Silk_Mapi_Model_Api2_Account
{
    /**
     * Create customer
     *
     * @param array $data
     * @return string
     */
    protected function _create(array $data)
    {
        $request = Mage::app()->getRequest();
        if (!isset($data['username']) || !isset($data['password'])) {
            $this->_critical(self::RESOURCE_REQUEST_DATA_INVALID);
        }

        $username = $data['username'];
        $password = $data['password'];

        if ($request->getHeader('App-Id') == 201) {
            return $this->loginByDeliver($username, $password, $request);
        }

        if (preg_match("/^[1][34578][0-9]{9}$/", $username)) {
            $email = "{$username}@hahahui.cn";
        } else {
            //使用用户名登录首先根据firstname获取email然后登录
            $collection = Mage::getModel('customer/customer')->getCollection()->addAttributeToFilter('firstname', array('eq' => $username));
            $model = $collection->getFirstItem();
            $email = $model->getEmail();
        }

        $websitId = 0;
        $collection = Mage::getModel('customer/customer')->getCollection()
            ->addAttributeToSelect('*')
            ->addAttributeToFilter('email', array('eq' => $email));

        if ($collection->count()) {
            $item = $collection->getFirstItem();
            $websitId = $item->getWebsiteId();
        }
        $customer = Mage::getModel('customer/customer')->setWebsiteId($websitId);
        $customer->loadByEmail($email);
        if (!$customer->getId()) {
            $this->_critical("用户名不存在！", 101001);
        }

        if ($customer->getConfirmation() && $customer->isConfirmationRequired()) {
            $this->_critical("您的帐号正在审核中，请稍候尝试登录！", 101002);
        }

        if (!$customer->validatePassword($password)) {
            $this->_critical("帐号错误或密码错误请核对后重试！", 101003);
        }

        $token = Mage::getModel('mapi/token');
        if ($customer->getId()) {
            $token->setCustomerId($customer->getId());
            $token->setWebsiteId($customer->getWebsiteId());
            $token->setAppid($request->getHeader('App-Id'));
            $token->setDeviceId($request->getHeader('Device-Id'));
            $token->save();
        }

        $storeCode = Mage::getModel('core/website')->load($websitId)->getDefaultStore()->getCode();

        if($storeCode == 'default')
        {
            $this->_critical("你的帐号尚未激活！请等待审核或者联系客服。", 101004);
        }

        $account = Mage::helper('rewardpoints/customer')->getAccountByCustomer($customer);
        $result = array(
            'token' => $token->getToken(),
            'token_secret' => $token->getTokenSecret(),
            'store' => $storeCode,
            'info' => array(
                'firstname' => $customer->getFirstname(),
                'lastname' => $customer->getLastname(),
                'mobile' => $customer->getMobile(),
                'points' => (int) $account->getPointBalance()
            ),
        );
        return $result;
    }

    /**
     * Retrieve information about customer
     *
     * @throws Mage_Api2_Exception
     * @return array
     */
    protected function _retrieve()
    {
        /** @var $customer Mage_Customer_Model_Customer */
        $customer = $this->_loadCustomerById($this->getRequest()->getParam('id'));
        return $customer->getData();
    }

    /**
     * Get customers list
     *
     * @return array
     */
    protected function _retrieveCollection()
    {
        $data = $this->_getCollectionForRetrieve()->load()->toArray();
        return isset($data['items']) ? $data['items'] : $data;
    }

    /**
     * Update customer
     *
     * @param array $data
     * @throws Mage_Api2_Exception
     */
    protected function _update(array $data)
    {
        /** @var $customer Mage_Customer_Model_Customer */
        $customer = $this->_loadCustomerById($this->getRequest()->getParam('id'));
        /** @var $validator Mage_Api2_Model_Resource_Validator_Eav */
        $validator = Mage::getResourceModel('api2/validator_eav', array('resource' => $this));

        $data = $validator->filter($data);

        unset($data['website_id']); // website is not allowed to change

        if (!$validator->isValidData($data, true)) {
            foreach ($validator->getErrors() as $error) {
                $this->_error($error, Mage_Api2_Model_Server::HTTP_BAD_REQUEST);
            }
            $this->_critical(self::RESOURCE_DATA_PRE_VALIDATION_ERROR);
        }

        $customer->addData($data);

        try {
            $customer->save();
        } catch (Mage_Core_Exception $e) {
            $this->_error($e->getMessage(), Mage_Api2_Model_Server::HTTP_INTERNAL_ERROR);
        } catch (Exception $e) {
            $this->_critical(self::RESOURCE_INTERNAL_ERROR);
        }
    }

    /**
     * Load customer by id
     *
     * @param int $id
     * @throws Mage_Api2_Exception
     * @return Mage_Customer_Model_Customer
     */
    protected function _loadCustomerById($id)
    {
        /** @var $customer Mage_Customer_Model_Customer */
        $customer = Mage::getModel('customer/customer')->load($id);
        if (!$customer->getId()) {
            $this->_critical(self::RESOURCE_NOT_FOUND);
        }
        return $customer;
    }

    protected function getTokenInfoByToken()
    {

    }

    protected function getTokenInfoByCustomer()
    {

    }

    protected function loginByDeliver($username, $password, $request)
    {
        /** @var Mage_Admin_Model_User $adminUserModel */
        $adminUserModel = Mage::getModel('admin/user');
        $adminUser = $adminUserModel->loadByUsername($username);
        if ($adminUser && $adminUser->getId() && $adminUser->getRole()->getId() == 5) {
            
            if (!Mage::helper('core')->validateHash($password, $adminUser->getPassword())) {
                $this->_critical("用户名或密码错误！", 101003);
            }

            $warehouseUser = Mage::getModel("zgb/warehouse")->load($adminUser->getId(), 'admin_id');
            if (!$warehouseUser || $warehouseUser->getStatus() != '1') {
                $this->_critical("你的帐号已被禁用！", 101002);
            }

            $token = Mage::getModel('mapi/token');
            if ($adminUser->getId()) {
                $token->setCustomerId($adminUser->getId());
                $token->setWebsiteId($adminUser->getWebsiteId());
                $token->setAppid($request->getHeader('App-Id'));
                $token->setDeviceId($request->getHeader('Device-Id'));
                $token->save();
            }

            //$storeCode = Mage::getModel('core/website')->load($adminUser->getWebsiteId())->getDefaultStore()->getCode();
            return array(
                'token' => $token->getToken(),
                'token_secret' => $token->getTokenSecret(),
                'info' => array(
                    'username' => $adminUser->getUsername(),
                    'mobile' => $adminUser->getPhone() ?: '',
                )
            );
        } else {
            $this->_critical("当前用户不存在！", 101001);
        }
    }

    /**
     * Retrieve collection instances
     *
     * @return Mage_Customer_Model_Resource_Customer_Collection
     */
    protected function _getCollectionForRetrieve()
    {
        /** @var $collection Mage_Customer_Model_Resource_Customer_Collection */
        $collection = Mage::getResourceModel('customer/customer_collection');
        $collection->addAttributeToSelect(array_keys(
            $this->getAvailableAttributes($this->getUserType(), Mage_Api2_Model_Resource::OPERATION_ATTRIBUTE_READ)
        ));

        $this->_applyCollectionModifiers($collection);
        return $collection;
    }
}
